package com.taritari.journal.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.taritari.journal.enums.ResultCode;
import com.taritari.journal.services.UserService;
import com.taritari.journal.utils.JwtUtil;
import com.taritari.journal.utils.Result;
import com.taritari.journal.utils.TokenUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;

import static java.sql.DriverManager.println;


/**
 * @author taritari
 * @date 2023-12-05 17:52
 * @description 拦截器
 */
@Configuration
public class MyInterceptor implements HandlerInterceptor {
    JwtUtil jwtUtil = new JwtUtil();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 检查是否存在 Authorization 头部
        String authorizationHeader = request.getHeader("Authorization");
        // 获取请求的URI
        String requestUri = request.getRequestURI();
        // 如果请求的是doc.html页面，则放行
        if ("/doc.html".equals(requestUri)||
                "/v3/api-docs/swagger-config".equals(requestUri)||
                "/v3/api-docs".equals(requestUri)||
                requestUri.contains("/webjars/")||
//                requestUri.contains("/journals/")||
                "/error".equals(requestUri)
        ) {
            return true;
        }
        if (authorizationHeader != null && !authorizationHeader.isEmpty()) {
            boolean tokenExpired = jwtUtil.isTokenExpired(authorizationHeader);
            if (tokenExpired) {
                String username = jwtUtil.getClaimFiled(authorizationHeader, "username");

                TokenUtils.setCurrentUser(username); // 设置当前用户

                return true;
            } else {
                sendErrorResponse(response, Result.fail(ResultCode.ERROR,"Token无效或已过期"));
                return false;
            }
        } else {
            sendErrorResponse(response, Result.fail(ResultCode.ERROR,"缺少Authorization头部，无效的请求"));
            return false;
        }
    }
    private void sendErrorResponse(HttpServletResponse response, Result message) throws IOException {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        PrintWriter writer = response.getWriter();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.writeValue(writer, message);
        writer.flush();
    }
}
